package eproject.mm.com.projectsupervision.activity;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.adapter.DataAdapter;
import eproject.mm.com.projectsupervision.adapter.MessageAdapter;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DataListActivity extends Activity implements OnItemClickListener {
    ListView dataList = null;
    DataAdapter adapter;
    LoadingDialog loadingDialog = null;
    private PtrClassicFrameLayout ptrFrameLayout;

    TextView tv_title;

    String type;
    int page = 1;
    List listData = new ArrayList();

    private AlertView mAlertView;
    int listPos;
    IconFontTextview iftv_back;
    private OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_list);

        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type","");

        initView();

        if(type.equals("planreport")){
            tv_title.setText("我的进度");
        }else if(type.equals("problem")){
            tv_title.setText("我的问题");
        }else if(type.equals("modify")){
            tv_title.setText("我的整改");
        }else if(type.equals("check")){
            tv_title.setText("我的复查");
        }

        //loadList();

        mAlertView = new AlertView("确认", "是否确认删除?", "取消", new String[]{"确定"}, null, this, AlertView.Style.Alert, this)
                .setCancelable(true);

        iftv_back = (IconFontTextview)findViewById(R.id.iftv_back);
        iftv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }
    public void initView(){
        tv_title = (TextView)findViewById(R.id.tv_title);
        dataList = (ListView) findViewById(R.id.dataList);
        dataList.setDivider(null);

        adapter = new DataAdapter(DataListActivity.this,listData);
        dataList.setAdapter(adapter);

        ptrFrameLayout = (PtrClassicFrameLayout)findViewById(R.id.ptrFL_message);

        //下拉刷新支持时间
        ptrFrameLayout.setLastUpdateTimeRelateObject(this);
        //下拉刷新一些设置 详情参考文档
        ptrFrameLayout.setResistance(1.7f);
        ptrFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
        ptrFrameLayout.setDurationToClose(200);
        ptrFrameLayout.setDurationToCloseHeader(1000);
        // default is false
        ptrFrameLayout.setPullToRefresh(false);
        // default is true
        ptrFrameLayout.setKeepHeaderWhenRefresh(true);
        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.autoRefresh(true);
            }
        }, 150);

        initEvent();
    }
    private void initEvent(){
        ptrFrameLayout.setPtrHandler(new com.chanven.lib.cptr.PtrDefaultHandler() {
            //在这里进行数据加载
            public void onRefreshBegin(com.chanven.lib.cptr.PtrFrameLayout frame) {
                page = 1;
                loadList();
            }
        });
        ptrFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                page++;
                loadList();
            }
        });

        dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                listPos = i;
                mAlertView.show();
            }
        });
    }

    private void loadList(){
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url  = "";
                    if(type.equals("planreport")){
                        url = "/getSchSubmitListByCreator";
                    }else if(type.equals("problem")){
                        url = "/getQuestionListByCreator";
                    }else if(type.equals("modify")){
                        url = "/getQuestionDealListByCreator";
                    }else if(type.equals("check")){
                        url = "/getQuestionCheckListByCreator";
                    }
                    String projectStr = HttpUtil.get(url+"?page="+page+"&limit=15");

                    handler.sendMessage(handler.obtainMessage(1, projectStr));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(DataListActivity.this,e.toString(),Toast.LENGTH_LONG);
                    handler.sendMessage(handler.obtainMessage(2, null));
                }
            }
        }).start();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String str = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(str, Map.class);
                    if (resultMap != null && (boolean) resultMap.get("success")) {
                        List rows = (List) resultMap.get("rows");
                        int pages = Integer.parseInt((String)resultMap.get("pages"));

                        loadingDialog.close();
                        if(page==1) {
                            listData.clear();
                            listData.addAll(rows);

                            adapter.notifyDataSetChanged();

                            ptrFrameLayout.refreshComplete();

                            if(page < pages){
                                if (!ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(true);
                                }
                            }
                        }else{
//                            msgAdapter.addItems(rows);
//                            msgList.setAdapter(msgAdapter);
                            listData.addAll(rows);
                            adapter.notifyDataSetChanged();

                            ptrFrameLayout.loadMoreComplete(true);
                            if(page == pages){
                                if (ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(false);
                                }
                            }
                        }
//
//                        dataList.deferNotifyDataSetChanged();
//
//                        loadingDialog.close();
//                        ptrFrameLayout.refreshComplete();
                    }
                    break;
                case 2:
                    loadingDialog.close();
                    ptrFrameLayout.refreshComplete();
                    if (ptrFrameLayout.isLoadMoreEnable()) {
                        ptrFrameLayout.setLoadMoreEnable(false);
                    }
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };

    @Override
    public void onItemClick(Object o, int position) {
        //判断是否是拓展窗口View，而且点击的是非取消按钮
        if (o == mAlertView && position != AlertView.CANCELPOSITION) {
            delete();
//            adapter.removeAt(listPos);
//            adapter.notifyDataSetChanged();
//            dataList.invalidate();
//
//            Toast.makeText(this, "删除", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private void delete(){
        //listPos
        final Map m = adapter.getItem(listPos);

        loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url  = "";
                    if(type.equals("planreport")){
                        url = "/deleteTask";
                    }else if(type.equals("problem")){
                        url = "/deleteProblem";
                    }else if(type.equals("modify")){
                        url = "/deleteProblemDeal";
                    }else if(type.equals("check")){
                        url = "/deleteProblemCheck";
                    }

                    try {
                        okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder();
                        builder.add("id",(String)m.get("id"));

                        RequestBody requestBody = builder.build();
                        Request.Builder okbuilder = new Request.Builder();
                        okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
                        Request requestPostCard = okbuilder
                                .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+url)
                                .post(requestBody)
                                .build();
                        client.newCall(requestPostCard).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                loadingDialog.close();
                            }

                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        loadingDialog.close();
                                        String str = "{}";
                                        try{
                                            ResponseBody body = response.body();
                                            if(body!=null) {
                                                str = body.string();
                                            }
                                        }catch (Exception ioe){

                                        }
                                        Gson gson=new Gson();
                                        Map resultMap = gson.fromJson(str, Map.class);
                                        if (resultMap != null && (boolean) resultMap.get("success")) {
                                            adapter.removeAt(listPos);
                                            adapter.notifyDataSetChanged();
                                        }else{
                                            String message = (String)resultMap.get("message");
                                            Toast.makeText(DataListActivity.this,message,Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        });
                    }catch (Exception e){
                        loadingDialog.close();
                    }
//                    String projectStr = HttpUtil.get(url+"?page="+page+"&limit=1");
//
//                    handler.sendMessage(handler.obtainMessage(1, projectStr));
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(DataListActivity.this,e.toString(),Toast.LENGTH_LONG);
                    handler.sendMessage(handler.obtainMessage(2, null));
                }
            }
        }).start();
    }
}
